const fs = require('fs');
const path = require('path');

class DocumentCleaner {
    constructor(configPath) {
        this.config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
        this.results = {
            deleted: [],
            archived: [],
            moved: [],
            errors: [],
            summary: {
                totalProcessed: 0,
                successCount: 0,
                errorCount: 0
            }
        };
    }

    async executeCleanup() {
        console.log('开始执行文档清理...');
        
        try {
            // 1. 创建归档目录
            await this.createArchiveStructure();
            
            // 2. 删除过时文件
            await this.deleteOutdatedFiles();
            
            // 3. 归档完成的项目目录
            await this.archiveCompletedProjects();
            
            // 4. 重新组织根目录
            await this.reorganizeRootDirectory();
            
            // 5. 生成清理报告
            this.generateCleanupReport();
            
            console.log('文档清理完成!');
            return this.results;
            
        } catch (error) {
            console.error('清理过程中出错:', error);
            this.results.errors.push({
                type: 'general_error',
                message: error.message,
                timestamp: new Date().toISOString()
            });
            throw error;
        }
    }

    async createArchiveStructure() {
        console.log('创建归档目录结构...');
        
        const archivePath = path.join(this.config.paths.docsRoot, 'archive');
        const timestamp = new Date().toISOString().split('T')[0]; // YYYY-MM-DD
        
        const archiveSubDirs = [
            'completed-projects',
            'outdated-docs',
            'deprecated-configs'
        ];
        
        try {
            // 创建主归档目录
            if (!fs.existsSync(archivePath)) {
                fs.mkdirSync(archivePath, { recursive: true });
                console.log(`创建归档目录: ${archivePath}`);
            }
            
            // 创建子目录
            for (const subDir of archiveSubDirs) {
                const subDirPath = path.join(archivePath, subDir);
                if (!fs.existsSync(subDirPath)) {
                    fs.mkdirSync(subDirPath, { recursive: true });
                    console.log(`创建归档子目录: ${subDirPath}`);
                }
            }
            
            // 创建时间戳目录
            const timestampPath = path.join(archivePath, 'outdated-docs', timestamp);
            if (!fs.existsSync(timestampPath)) {
                fs.mkdirSync(timestampPath, { recursive: true });
                console.log(`创建时间戳目录: ${timestampPath}`);
            }
            
        } catch (error) {
            console.error('创建归档结构失败:', error);
            this.results.errors.push({
                type: 'archive_structure_error',
                message: error.message,
                timestamp: new Date().toISOString()
            });
        }
    }

    async deleteOutdatedFiles() {
        console.log('删除过时文件...');
        
        const outdatedFiles = [
            'AUTOMATION_CONFIG.md',
            'MAINTENANCE_GUIDE.md',
            'NAVIGATION.md',
            'QUALITY_CHECKLIST.md',
            'UI_ISSUES_ANALYSIS.md',
            'UI_REPAIR_APPROVAL.md',
            'UI_REPAIR_TASKS.md',
            'VERSION_CONTROL_GUIDE.md'
        ];
        
        const timestamp = new Date().toISOString().split('T')[0];
        const archivePath = path.join(this.config.paths.docsRoot, 'archive', 'outdated-docs', timestamp);
        
        for (const fileName of outdatedFiles) {
            try {
                const filePath = path.join(this.config.paths.docsRoot, fileName);
                
                if (fs.existsSync(filePath)) {
                    // 先移动到归档目录，而不是直接删除
                    const archiveFilePath = path.join(archivePath, fileName);
                    fs.copyFileSync(filePath, archiveFilePath);
                    fs.unlinkSync(filePath);
                    
                    this.results.archived.push({
                        originalPath: filePath,
                        archivePath: archiveFilePath,
                        type: 'outdated_file',
                        timestamp: new Date().toISOString()
                    });
                    
                    console.log(`归档过时文件: ${fileName}`);
                    this.results.summary.successCount++;
                } else {
                    console.log(`文件不存在，跳过: ${fileName}`);
                }
                
                this.results.summary.totalProcessed++;
                
            } catch (error) {
                console.error(`处理文件失败 ${fileName}:`, error);
                this.results.errors.push({
                    type: 'file_operation_error',
                    file: fileName,
                    message: error.message,
                    timestamp: new Date().toISOString()
                });
                this.results.summary.errorCount++;
            }
        }
    }

    async archiveCompletedProjects() {
        console.log('归档完成的项目目录...');
        
        const projectsToArchive = [
            '6A-diagram-regeneration',
            'flutter-app-optimization',
            'hrc_doc_optimization',
            'prototype-update'
        ];
        
        const archivePath = path.join(this.config.paths.docsRoot, 'archive', 'completed-projects');
        
        for (const projectDir of projectsToArchive) {
            try {
                const sourcePath = path.join(this.config.paths.docsRoot, projectDir);
                const targetPath = path.join(archivePath, projectDir);
                
                if (fs.existsSync(sourcePath)) {
                    // 递归复制目录
                    this.copyDirectoryRecursive(sourcePath, targetPath);
                    
                    // 删除原目录
                    this.removeDirectoryRecursive(sourcePath);
                    
                    this.results.archived.push({
                        originalPath: sourcePath,
                        archivePath: targetPath,
                        type: 'completed_project',
                        timestamp: new Date().toISOString()
                    });
                    
                    console.log(`归档项目目录: ${projectDir}`);
                    this.results.summary.successCount++;
                } else {
                    console.log(`目录不存在，跳过: ${projectDir}`);
                }
                
                this.results.summary.totalProcessed++;
                
            } catch (error) {
                console.error(`归档项目目录失败 ${projectDir}:`, error);
                this.results.errors.push({
                    type: 'directory_operation_error',
                    directory: projectDir,
                    message: error.message,
                    timestamp: new Date().toISOString()
                });
                this.results.summary.errorCount++;
            }
        }
    }

    async reorganizeRootDirectory() {
        console.log('重新组织根目录...');
        
        // 创建新的组织结构
        const newStructure = {
            'active-projects': ['prototype-optimization', 'doc-cleanup'],
            'documentation': ['product', 'technical', 'user-guide'],
            'infrastructure': ['security', 'deployment', 'assets']
        };
        
        try {
            for (const [categoryDir, items] of Object.entries(newStructure)) {
                const categoryPath = path.join(this.config.paths.docsRoot, categoryDir);
                
                // 创建分类目录
                if (!fs.existsSync(categoryPath)) {
                    fs.mkdirSync(categoryPath, { recursive: true });
                    console.log(`创建分类目录: ${categoryDir}`);
                }
                
                // 移动相关项目到分类目录
                for (const item of items) {
                    const sourcePath = path.join(this.config.paths.docsRoot, item);
                    const targetPath = path.join(categoryPath, item);
                    
                    if (fs.existsSync(sourcePath) && !fs.existsSync(targetPath)) {
                        if (fs.statSync(sourcePath).isDirectory()) {
                            this.copyDirectoryRecursive(sourcePath, targetPath);
                            this.removeDirectoryRecursive(sourcePath);
                        } else {
                            fs.copyFileSync(sourcePath, targetPath);
                            fs.unlinkSync(sourcePath);
                        }
                        
                        this.results.moved.push({
                            from: sourcePath,
                            to: targetPath,
                            type: 'reorganization',
                            timestamp: new Date().toISOString()
                        });
                        
                        console.log(`移动到分类: ${item} -> ${categoryDir}`);
                    }
                }
            }
            
        } catch (error) {
            console.error('重新组织目录失败:', error);
            this.results.errors.push({
                type: 'reorganization_error',
                message: error.message,
                timestamp: new Date().toISOString()
            });
        }
    }

    copyDirectoryRecursive(source, target) {
        if (!fs.existsSync(target)) {
            fs.mkdirSync(target, { recursive: true });
        }
        
        const items = fs.readdirSync(source);
        
        for (const item of items) {
            const sourcePath = path.join(source, item);
            const targetPath = path.join(target, item);
            
            if (fs.statSync(sourcePath).isDirectory()) {
                this.copyDirectoryRecursive(sourcePath, targetPath);
            } else {
                fs.copyFileSync(sourcePath, targetPath);
            }
        }
    }

    removeDirectoryRecursive(dirPath) {
        if (fs.existsSync(dirPath)) {
            const items = fs.readdirSync(dirPath);
            
            for (const item of items) {
                const itemPath = path.join(dirPath, item);
                
                if (fs.statSync(itemPath).isDirectory()) {
                    this.removeDirectoryRecursive(itemPath);
                } else {
                    fs.unlinkSync(itemPath);
                }
            }
            
            fs.rmdirSync(dirPath);
        }
    }

    generateCleanupReport() {
        const reportPath = path.join(this.config.paths.workingDir, 'validation', 'cleanup-report.json');
        
        const report = {
            timestamp: new Date().toISOString(),
            summary: this.results.summary,
            operations: {
                archived: this.results.archived,
                moved: this.results.moved,
                deleted: this.results.deleted
            },
            errors: this.results.errors,
            statistics: {
                archivedCount: this.results.archived.length,
                movedCount: this.results.moved.length,
                deletedCount: this.results.deleted.length,
                errorCount: this.results.errors.length,
                successRate: this.results.summary.totalProcessed > 0 ? 
                    (this.results.summary.successCount / this.results.summary.totalProcessed * 100).toFixed(2) + '%' : '0%'
            }
        };
        
        fs.writeFileSync(reportPath, JSON.stringify(report, null, 2));
        console.log(`清理报告已生成: ${reportPath}`);
        
        // 生成人类可读的报告
        this.generateHumanReadableCleanupReport(report);
    }

    generateHumanReadableCleanupReport(report) {
        const reportPath = path.join(this.config.paths.workingDir, 'validation', 'cleanup-summary.md');
        
        let content = `# 文档清理执行报告\n\n`;
        content += `执行时间: ${report.timestamp}\n\n`;
        
        content += `## 执行概要\n\n`;
        content += `- 总处理项目: ${report.summary.totalProcessed}\n`;
        content += `- 成功操作: ${report.summary.successCount}\n`;
        content += `- 失败操作: ${report.summary.errorCount}\n`;
        content += `- 成功率: ${report.statistics.successRate}\n\n`;
        
        content += `## 操作统计\n\n`;
        content += `- 归档项目: ${report.statistics.archivedCount}\n`;
        content += `- 移动项目: ${report.statistics.movedCount}\n`;
        content += `- 删除项目: ${report.statistics.deletedCount}\n`;
        content += `- 错误数量: ${report.statistics.errorCount}\n\n`;
        
        if (report.operations.archived.length > 0) {
            content += `## 归档操作\n\n`;
            report.operations.archived.forEach(op => {
                content += `- ${op.type}: ${path.basename(op.originalPath)} -> ${path.relative(this.config.paths.docsRoot, op.archivePath)}\n`;
            });
            content += `\n`;
        }
        
        if (report.operations.moved.length > 0) {
            content += `## 移动操作\n\n`;
            report.operations.moved.forEach(op => {
                content += `- ${path.basename(op.from)} -> ${path.relative(this.config.paths.docsRoot, op.to)}\n`;
            });
            content += `\n`;
        }
        
        if (report.errors.length > 0) {
            content += `## 错误记录\n\n`;
            report.errors.forEach(error => {
                content += `- ${error.type}: ${error.message}\n`;
            });
            content += `\n`;
        }
        
        content += `## 新的目录结构\n\n`;
        content += `\`\`\`\n`;
        content += `docs/\n`;
        content += `├── active-projects/\n`;
        content += `│   ├── prototype-optimization/\n`;
        content += `│   └── doc-cleanup/\n`;
        content += `├── documentation/\n`;
        content += `│   ├── product/\n`;
        content += `│   ├── technical/\n`;
        content += `│   └── user-guide/\n`;
        content += `├── infrastructure/\n`;
        content += `│   ├── security/\n`;
        content += `│   ├── deployment/\n`;
        content += `│   └── assets/\n`;
        content += `└── archive/\n`;
        content += `    ├── completed-projects/\n`;
        content += `    ├── outdated-docs/\n`;
        content += `    └── deprecated-configs/\n`;
        content += `\`\`\`\n\n`;
        
        fs.writeFileSync(reportPath, content);
        console.log(`可读清理报告已生成: ${reportPath}`);
    }
}

// 如果直接运行此脚本
if (require.main === module) {
    const configPath = path.join(__dirname, 'config.json');
    const cleaner = new DocumentCleaner(configPath);
    
    cleaner.executeCleanup()
        .then(results => {
            console.log('\n=== 清理完成 ===');
            console.log(`总处理项目: ${results.summary.totalProcessed}`);
            console.log(`成功操作: ${results.summary.successCount}`);
            console.log(`失败操作: ${results.summary.errorCount}`);
            
            if (results.errors.length > 0) {
                console.log('\n错误详情:');
                results.errors.forEach(error => {
                    console.log(`- ${error.type}: ${error.message}`);
                });
            }
        })
        .catch(error => {
            console.error('清理过程失败:', error);
            process.exit(1);
        });
}

module.exports = DocumentCleaner;